package script

import (
	"context"
	"gitee.com/kmyss/gf-ex/yscmd"
	"gitee.com/kmyss/gf-ex/yslog"
	"gitee.com/kmyss/gf-ex/ysos"
	"gitee.com/kmyss/gf-ex/ysutils"
	"gitee.com/kmyss/ys-cli/internal/model"
	"gitee.com/kmyss/ys-cli/internal/service"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
)

func init() {
	service.RegisterScript(&sScript{})
}

type sScript struct {
	l *glog.Logger // 日志
}

func (s *sScript) log() *glog.Logger {
	if s.l == nil {
		s.l = yslog.Log("logic.script")
	}
	return s.l
}

func (s *sScript) Run(ctx context.Context, in *model.ScriptRunInput) (err error) {

	if g.IsEmpty(in.Script) {
		in.Script, err = s.selectScript(ctx, in.Path)
		if err != nil {
			return
		}

	}

	script, err := s.scanScript(ctx, in.Path)
	if err != nil {
		return
	}
	cmd, ok := script[in.Script]
	if !ok {
		if g.IsEmpty(in.Script) {
			yslog.Error("请输入脚本命令")
		} else {
			yslog.Errorf(" %s 命令不存在！", in.Script)
		}

		yslog.Print("可以使用的命令如下")
		for key := range script {
			yslog.Print(key)
		}

		return
	}

	err = s.runScript(ctx, cmd)
	if err != nil {
		return
	}

	return
}

func (s *sScript) selectScript(ctx context.Context, in string) (out string, err error) {
	script, err := s.scanScript(ctx, in)
	if err != nil {
		return
	}

	if len(script) == 0 {
		err = gerror.New("没有找到可用的脚本文件！")
		return
	}

	// 对脚本数据进行排序
	keys := make([]string, 0, len(script))
	for key := range script {
		keys = append(keys, key)
	}
	arrayComparator := garray.NewSortedStrArrayComparator(func(a, b string) int {
		result := ysutils.FileNumToInt(a) - ysutils.FileNumToInt(b)
		yslog.Debugf("处理结果[%s],[%s],[%d]", a, b, result)
		if result > 0 {
			return 1
		} else if result < 0 {
			return -1
		}
		return 0
	})
	arrayComparator.Append(keys...)

	// 读取脚本
	out, _ = yscmd.SelectOne(arrayComparator.Slice(), "请选择一个脚本")

	return
}

func (s *sScript) runScript(ctx context.Context, in string) (err error) {
	return ysos.RunShellFile(ctx, in)
}
